<?php

namespace app\common\model;

use app\lib\enum\Status;
use think\Exception;

class CmsArticleCategory extends BaseModel
{
    //通过分类获取文章信息
    public function bindArticle(){
        return $this->hasMany("CmsArticle","art_category_id","acc_id");
    }

    //添加
    public function articleCategoryAdd($data){
        $acc_name=$data['acc_name'];
        $isset=$this->where("acc_name","=",$acc_name)->find();
        if($isset){
            return "该分类名已存在";
        }
        //如果传入父分类id，要进行校验，判断传过来的父分类id是否存在，且是个父类
        if(isset($data['acc_parent_id'])&&$data['acc_parent_id']!=-1){
            $isset=$this->find($data['acc_parent_id']);
            if(!$isset){
                return "父分类不存在";
            }
            if($isset['acc_parent_id']!=-1){
                return "请选择父级分类创建子分类";
            }
        }

        $data['acc_status']=isset($data['acc_status'])&&$data['acc_status']=="on"?Status::on:Status::off;
        $data=$this->dataFilter($data);
        try{
            $result=$this->insert($data);
        }catch (Exception $e){
            return "数据添加异常";
        }
        if(!$result){
            return "数据添加失败";
        }else{
            return 1;
        }
    }

    //编辑
    public function articleCategoryEdit($data,$acc_id){
        $categoryInfo=$this->find($acc_id);
        if($categoryInfo['acc_name']!=$data['acc_name']&&$this->where("acc_name","=",$data['acc_name'])->find()){
            return "该分类名已存在";
        }
        $data['acc_status']=isset($data['acc_status'])&&$data['acc_status']=="on"?Status::on:Status::off;
        $data=$this->dataFilter($data);
        try{
            $result=$this->where("acc_id","=",$acc_id)->update($data);
        }catch (Exception $e){
            return "数据更新异常";
        }
        if(!$result){
            return "数据未发生变化";
        }else{
            return 1;
        }

    }

    //获取首页资讯信息
    public function getIndexArticleInfo(){
//        $articleInfo=$this->with("bindArticle")->where("acc_status","=",Status::on)->select();
        $articleInfo=[];
        $categoryInfo=$this->select();
        $pageNum=config("indexSetting.indexArticleNum");
        foreach($categoryInfo as $value){
            $acc_id=$value['acc_id'];
            $articleItemInfo=model("JhArticle")->where("art_category_id","=",$acc_id)->order("art_order","asc")
                ->limit($pageNum)->select();
            $value['bindArticle']=$articleItemInfo;
            $articleInfo[]=$value;
        }
        return $articleInfo;
    }
}
